package edu.uic.kott.fragments;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import edu.uic.keyoutcomestrackertool.R;
import edu.uic.kott.activities.TrackKeyOutcomes;
import edu.uic.kott.db.KottDataSource;
import edu.uic.kott.model.Course;
import edu.uic.kott.model.Instructor;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.Toast;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.TextView;

public class TrackAttendance extends Fragment {

	//Representing focused date selected in Calendar Fragment
	static TextView classAttendanceOn;
	static String attendanceDate;
	public static Context attendanceContext;

	Button attendanceRefreshButton;

	//Dynamic GUI holder
	static TableLayout attendanceQueryLayout;

	//Data
	static KottDataSource datasource;
	List<Course> coursesList;

	private String LOGTAG = "KOTT";

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View track_attendance_view = inflater.inflate(R.layout.track_attendance, container, false);

		//Representing text view showing active date
		classAttendanceOn = (TextView) track_attendance_view.findViewById(R.id.classAttendanceOn);
		classAttendanceOn.setText(TrackKeyOutcomes.activeDate);

		attendanceRefreshButton = (Button) track_attendance_view.findViewById(R.id.attendanceRefreshButton);
		attendanceRefreshButton.setOnClickListener(attendanceRefreshListener);

		attendanceQueryLayout = (TableLayout) track_attendance_view.findViewById(R.id.attendanceQueryLayout);

		//Returns to TrackKeyOutcomes that this fragment is visible
		TrackKeyOutcomes.attendanceVisible = true;
		TrackKeyOutcomes.UpdateVariables();

		AttendanceData(attendanceDate);

		return track_attendance_view;
	}

	public OnClickListener attendanceRefreshListener = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			//Remove all classes if any exist
			removeAllViews();

			//Populate view with classes on refresh date
			AttendanceData(attendanceDate);

			Log.i("Refresh", "Displaying classes on: " + attendanceDate);
		}

	};

	public void makeAttendanceGUI(String classId, String className, String courseNumber, String startTime, String instructor,
			String ta, String classLocation, int index) {
		LayoutInflater inflater = (LayoutInflater) this.getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		View newRowView = inflater.inflate(R.layout.attendance_group_view, null);

		TextView classText = (TextView) newRowView.findViewById(R.id.classNameTextView);
		classText.setText(className);

		TextView courseText = (TextView) newRowView.findViewById(R.id.attendanceCourseNumber);
		courseText.setText(courseNumber);

		TextView timeText = (TextView) newRowView.findViewById(R.id.attendanceTimeOfClass);
		timeText.setText(startTime);

		TextView instructorText = (TextView) newRowView.findViewById(R.id.attendanceClassInstructor);
		instructorText.setText(instructor);

		TextView taText = (TextView) newRowView.findViewById(R.id.attendanceClassTA);
		taText.setText(ta);

		TextView locationText = (TextView) newRowView.findViewById(R.id.attendanceClassLocation);
		locationText.setText(classLocation);

		CheckBox attendedCheck = (CheckBox) newRowView.findViewById(R.id.attendanceAttendedCheckBox);
		attendedCheck.setOnCheckedChangeListener(attendedBoxListener);

		CheckBox cancelledCheck = (CheckBox) newRowView.findViewById(R.id.attendanceCancelledCheckBox);
		cancelledCheck.setOnCheckedChangeListener(cancelledBoxListener);

		TextView weekToDate = (TextView) newRowView.findViewById(R.id.attendanceWeekToDate);
		weekToDate.setText(this.getActivity().getResources().getString(R.string.weekToDateAttendance) + " " + String.valueOf(WeekToDateAttendance(classId)));

		TextView termToDate = (TextView) newRowView.findViewById(R.id.attendanceTermToDate);
		termToDate.setText(this.getActivity().getResources().getString(R.string.termToDateAttendance) + " " + String.valueOf(TermToDateAttendance(classId)));

		//Sets tag for view as the unique classId
		newRowView.setTag(classId);

		attendanceQueryLayout.addView(newRowView, index);
	}

	private long TermToDateAttendance(String id) {

		int scheduled = 9;
		int attended = 9;

		long percentage = attended/scheduled;

		return percentage;
	}

	private long WeekToDateAttendance(String id) {

		int scheduled = 3;
		int attended = 3;

		long percentage = attended/scheduled;


		return percentage;
	}

	public static void AttendanceUpdateOnDateChange() {
		//Updates active date to match date touched within Calendar fragment
		//Is called by TrackKeyOutcomes class
		attendanceDate = TrackKeyOutcomes.activeDate;
		classAttendanceOn.setText("On: " + attendanceDate);
		removeAllViews();
	}

	private static void removeAllViews() {
		attendanceQueryLayout.removeAllViews();
	}

	@Override
	public void onStop() {
		TrackKeyOutcomes.attendanceVisible = false;
		super.onStop();
	}

	@Override
	public void onResume() {
		TrackKeyOutcomes.attendanceVisible = true;
		super.onResume();
	}

	public static OnCheckedChangeListener attendedBoxListener = new OnCheckedChangeListener() {

		@Override
		public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
			//Get classId of box via group tag
			LinearLayout group = (LinearLayout) buttonView.getParent().getParent();
			String classId = (String) group.getTag();

			//String of isChecked boolean variable for logging purposes
			String attended = String.valueOf(isChecked);

			//Log.i(classId, "attended = " + attended);

			//Get the date
			String date = attendanceDate;

			datasource.markAttended(classId,date);

			//Database put code

			//Log.i(classId, "attended on " + date + ": " + attended);

		}
	};

	public static OnCheckedChangeListener cancelledBoxListener = new OnCheckedChangeListener() {

		@Override
		public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
			//Get classId of box via group tag
			LinearLayout group = (LinearLayout) buttonView.getParent().getParent();
			long classId = (Long) group.getTag();

			//String of isChecked boolean variable for logging purposes
			String cancelled = String.valueOf(isChecked);

			Log.i(String.valueOf(classId), "cancelled = " + cancelled);

			//Get the date
			String date = attendanceDate;

			//Database put code
			datasource.markCanceled(String.valueOf(classId),date);

			Log.i(String.valueOf(classId), "cancelled on " + date + ": " + cancelled);


		}
	};

	public void AttendanceData(String date) {

		Toast.makeText(this.getActivity(), "Loading classes...", Toast.LENGTH_SHORT).show();

		datasource = new KottDataSource(this.getActivity());

		//Run query to find courses on this date
		Course c = new Course();

		List<String> courseIdsForDate = new ArrayList<String>();

		List<Course> courseList = new ArrayList<Course>(); 
		courseList = datasource.findAllCourses("trackAtten");

		for (Course course : courseList) {
			String id = String.valueOf(course.getCourseId());
			
			List<String> classDates = datasource.allClassDates(id);
			
			if (classDates.contains(attendanceDate)) {
				courseIdsForDate.add(id);	
			}
			
		}


		//courseIdsForDate = datasource.getCourseForDate(attendanceDate);

		//MAKE GUI
		for (String id : courseIdsForDate) {

			
			c = datasource.getCourseDetails(id);
			Log.i(LOGTAG,".............jgv................... " + id);
			
			//long courseId = c.getCourseId();
			//Log.i(LOGTAG,"................................ " + courseId));
			String courseName = c.getCourseName();
			String startTime = c.getStartTime();
			String instructorName = c.getInstructor();
			String taName = c.getTa();
			String classLocation = c.getClassLocation();
			
			

			makeAttendanceGUI(id, courseName, null, startTime, instructorName, taName, classLocation, 0);
		}

		//Above should end up looping like this
		//makeAttendanceGUI(0 /*this is id*/, "Elementary Linear Algebra", "MATH120", "1:00", "Timothy Doyle", "This is a sample", "LCD 1", 0);
		//makeAttendanceGUI(1, "Competitive Strategy", "IDS495", "3:30", "Mary Beth Watson-Manheim", "This is a sample 2", "Douglas Hall 230", 1);
	}

}
